﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace MSMQ试用
{
    class Program
    {

      static  System.Threading.SemaphoreSlim wait = new System.Threading.SemaphoreSlim(100, 10000);

        static long write=0;
      static  long read=0;
        static void Main(string[] args)
        {
            int n = 0;
            writeReadTest(n);
            //n++;
            writeReadTest(n);
            //n++;
            writeReadTest(n);

            Task.Factory.StartNew(() => {
                long w=0;
                 while (true)
                {

                    long sp = write - w;
                    w = write;
                    Console.WriteLine("写：{0:N};读：{1:N};速度：{2:N}^", write,read, sp/10.0);
                    System.Threading.Thread.Sleep(10000);
                }
            });
            while (true)
            {
                Console.Read();
            }
        }
        //创建读写线程测试
        static void writeReadTest(int n=0)
        {
            //
            Task.Factory.StartNew(() => {
                MSMQ读取写入 mq = new MSMQ读取写入();
                mq.Init(n);
                // System.Threading.Thread.Sleep(10000);
                while (true)
                {
                    System.Threading.Interlocked.Increment(ref read);
                    mq.GetMsg();
                    wait.Wait();
                }
            });
            Task.Factory.StartNew(() => {
                MSMQ读取写入 mq = new MSMQ读取写入();
                mq.Init(n);
                while (true)
                {
                    if (wait.CurrentCount < 10000 - 1000)
                    {
                        System.Threading.Interlocked.Increment(ref write);
                        mq.SendMsg();
                        wait.Release();
                    }
                    else {
                        System.Threading.Thread.Sleep(1000);
                    }

                }
            });
        }
    }
}
